package com.cskaoyan.config.shiro;

import com.cskaoyan.bean.administrators.Admin;
import com.cskaoyan.service.AdministratorsService;
import com.cskaoyan.util.Md5HashUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

/**
 * @Description: admin所需的realm
 * @Author: WD created on 2021-09-18 10:49
 * @Version:
 */
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    AdministratorsService administratorsService;

    //授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了doGetAuthorizationInfo方法");
        String username= (String) principalCollection.getPrimaryPrincipal();
        Admin admin = administratorsService.getAdmin(username);
        List<String> perms = administratorsService.getPerms(admin);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    //认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了doGetAuthenticationInfo方法");
        UsernamePasswordToken tokens = (UsernamePasswordToken) token;
        //用户输入的密码加密
        char[] originPassword = tokens.getPassword();
        String originPassword1 = new String(originPassword);
        char[] newPassword = Md5HashUtil.Md5encryption(originPassword1).toCharArray();
        tokens.setPassword(newPassword);
        Admin admin = administratorsService.getAdmin(tokens.getUsername());



        if (admin == null) {
            //用户名不存在
            //shiro底层就会抛出 UnknownAccountException
            return null;
        }
        //第一个参数：放入到系统中的用户信息,塞入的是什么类型的用户信息，后续取出就是什么类型的
        //这里塞入的admin的所有信息
        //第二个参数：系统中维护的正确的密码
        return new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), admin.getUsername());
        //认证器在认证过程中：会比对token中的password和authenticationInfo中的password，不同会抛出异常
    }
}
